'use strict'
const jwt = require('../middlewares/jwt')
const config = require('../utils/config')
const userService = require('../services').UserService
const registry = async (ctx, next) => {
    const {
        username,
        password
    } = ctx.request.body
    if (!username || !password) {
        console.log('用户名和密码不能为空')
    }
    const user = await userService.registry(
        username,
        password
    )
    if (user?.dataValues) {
        ctx.result = '注册成功'
    }else if(user.id){
         ctx.result = '注册失败，用户名已存在！'
    }else{
        ctx.result='注册失败'
    }
    return next()
}
const login = async (ctx,next)=>{
    const {
        username,
        password
    } = ctx.request.body
    if (!username || !password) {
        console.log('用户名和密码不能为空')
    }

    const user = await userService.login(
        username,
        password
    )

    if (user?.dataValues) {
        ctx.result = jwt.signToken(user?.dataValues)
    }
    return next()
}

const getUserInfoMe= async (ctx,next)=>{
    if (ctx.jwtData) {
        // 此处根据解密后的jwtData去获取用户详情
        const user = await userService.getUserInfo(ctx.params.id)

        const {
            id,
            username,
        } = user.dataValues

        ctx.result = {
            id,
            username
        }
    }
    return next();
}

const getUserList = async (ctx, next) => {
        console.log(ctx.jwtData)
        if (ctx.jwtData) {
            // 此处根据解密后的jwtData去获取用户详情
            const userList = await userService.getUserList()
            ctx.result = userList.map(item => item.dataValues)
            console.log(ctx.result)
        }
        return next()

}



module.exports={
   registry,login, getUserInfoMe, getUserList
}